package directory;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import com.google.appengine.api.blobstore.BlobInfo;
//import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class ListMediaFiles extends HttpServlet {
	
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
        BlobKey blobKey = blobs.get("fileName");
        
        
        BlobInfoFactory blobInfoFactory = new BlobInfoFactory();
        BlobInfo blobInfo = blobInfoFactory.loadBlobInfo(blobKey);
		        
		Key audioFileKey = KeyFactory.createKey("AudioFiles", "mediaFiles");
		String mediaName = req.getParameter("mediaName");
		String mediaType = req.getParameter("mediaType");
		AddEntity(audioFileKey, mediaName, mediaType, blobKey);
		
		Entity audioInfo = new Entity("Audio", audioFileKey);
		// This is all the metadata - not sure if we should put this in the datastore or just 
		// load it up when needed.
		
		audioInfo.setProperty("fileName", blobInfo.getFilename());
		audioInfo.setProperty("fileSize", blobInfo.getSize());
		audioInfo.setProperty("dateCreated", blobInfo.getCreation());
		
	
		if (blobKey == null) {
			resp.sendRedirect("/upload.jsp");
		} else {
			resp.sendRedirect("/uploadSuccessful.jsp");
		}
	}
	
	public static void AddEntity(Key _key, String _mediaName, String _mediaType, BlobKey _blobKey) {
		Entity audioInfo = new Entity("Audio", _key);
		//audioInfo.setProperty("user", user name);
		audioInfo.setProperty("mediaName", _mediaName);
		audioInfo.setProperty("mediaType", _mediaType);
		audioInfo.setProperty("blobKey", _blobKey);
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		datastore.put(audioInfo);
	}
}
